﻿using System;
using System.Collections.Generic;
using DT.Core.Models;
using Furion.DynamicApiController;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using SqlSugar;

namespace XCPFrame.Application.Api
{
    /// <summary>
    /// 系统管理
    /// </summary>
    [AppAuthorize, ApiDescriptionSettings("目录节点管理")]
    public class NodeApiService : IDynamicApiController
    {
        private readonly ISqlSugarRepository repository;
        private readonly SqlSugarClient db;

        public NodeApiService(ISqlSugarRepository sqlSugarRepository)
        {
            repository = sqlSugarRepository;
            db = repository.Context;
        }

        /// <summary>
        /// 获取后台主菜单信息
        /// </summary>
        /// <param name="rootid"></param>
        /// <returns></returns>
        public List<SysNode> GetNodeTree(int rootid = 0)
        {
            List<SysNode> rs = new List<SysNode>();

            //获取指定id上面的所有父节点,由下至上
            //rs = db.Queryable<SysNode>().ToParentList(it => it.Pid, rootid);

            //根据pid查询所有子节点集,由上至下。
            rs = db.Queryable<SysNode>().ToTree(it => it.Children, it => it.Pid, 0);

            //手动关联一级级联
            //rs = db.Queryable<SysNode>()
            //       .Mapper(it => it.Parent, it => it.Pid, it => it.Parent.Id)
            //       .Mapper(it => it.Children, it => it.Id, it => it.Parent.Pid)
            //       .Where(w => w.Pid == rootid)
            //       .ToList();

            return rs;
        }

        /// <summary>
        /// 添加新菜单目录节点
        /// </summary>
        /// <param name="node"></param>
        /// <returns></returns>
        public int AddNode(SysNode node)
        {
            int rs = 0;

            if (node.Id == 0)
            {
                //node.Id = new SysNode().Id;
                bool sucess = db.Insertable<SysNode>(node).IgnoreColumns(ignoreNullColumn: true).ExecuteCommandIdentityIntoEntity();
            }
            else
            {
                rs = db.Updateable(node).ExecuteCommand();
            }

            return rs;
        }

        /// <summary>
        /// 更新菜单目录节点
        /// </summary>
        /// <param name="node"></param>
        /// <returns></returns>
        public int UpdateNode(SysNode node)
        {
            int rs = 0;

            rs = db.Updateable(node).ExecuteCommand();

            return rs;
        }

        /// <summary>
        /// 删除菜单目录节点,自动删除所有子级节点和自己目录
        /// </summary>
        /// <param name="node"></param>
        /// <returns></returns>
        public int DeleteNode(SysNode node)
        {
            int rs = 0;

            List<SysNode> list = db.Queryable<SysNode>().ToTree(it => it.Children, it => it.Pid, node.Id);

            list.Add(node);

            rs = db.Deleteable<SysNode>(list).ExecuteCommand();

            return rs;
        }

    }
}
